package L7.L716;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 对角线遍历
 *
 * @author: luolidong
 * @create: 2021-07-16 15:43
 * @version: 1.0
 */
public class Demo1 {
    public int[] findDiagonalOrder(int[][] mat) {
        if(mat.length==0) return new int[0];
        List<Integer> list = new ArrayList<>();
        int len = mat.length;
        int len1 = mat[0].length;

        int count = 0;
        int x, y;
        while (count < len + len1 - 1) {
            //向斜上遍历，要确定开始的位置
            if (count % 2 == 0) {
                if (count < len) {
                    x = count;
                } else {
                    x = len - 1;//代表在最底层
                }
                y = count - x;

                while (x >= 0 && y < len1) {
                    list.add(mat[x][y]);
                    x--;
                    y++;
                }
            } else {
                //向斜下遍历，要确定开始的位置
                if (count < len1) {
                    y = count;
                } else {
                    y = len1 - 1;//代表在最右侧
                }
                x = count - y;
                while (x < len && y >= 0) {
                    list.add(mat[x][y]);
                    x++;
                    y--;
                }
            }
            count--;
        }

        int[] ans = new int[list.size()];
        for (int i = 0; i < list.size(); i++) {
            ans[i] = list.get(i);
        }
        return ans;
    }
}
